import api from '@/plug-in/api';
import Vue from 'vue';

export default {
  namespaced: true, // 添加上命名空间，定义为模块
  state: {
    token: null,
    profile: null,
    bindings: null
  },
  getters: {
    // xxx() { return xxx; }
  },
  mutations: {
    // 该对象存放的是同步的操作
    // changelist(state, { name, objData }) { state.studentList.push(objData); }
    SET_user(state, userData) {
      ['profile', 'bindings', 'token'].forEach((key) => {
        const item = userData[key];
        if (item) state[key] = item;
      });
      // console.log(JSON.stringify(state, null, 2));
    },
    SET_clear_user(state) {
      [...Object.keys(state)].forEach((key) => {
        state[key] = null;
      });
    }
  },
  actions: {
    // 执行异步的，可以重名
    updateLoginState({ commit }) {
      const userData = {};
      api.post('login_refresh').then((data) => api.post('login_status')).then(({ bindings, profile: { userId } }) => {
        userData.bindings = bindings;
        return api.post('user_detail', { uid: userId }, true);
      }).then(({ profile }) => {
        userData.profile = profile;
        commit('SET_user', userData);
      });
    },
    logout({ commit }) {
      api.get('login_logout', { _: +new Date() }, true).then(() => {
        commit('SET_clear_user');
        Vue.prototype.$message({
          showClose: true,
          type: 'success',
          message: '已退出登录'
        });
      });
    }
  }
};
